import http from '@/api/http.js'
import store from '@/store/index.js'

const requestUserInfo = function(code, encryptedData, iv, user_info, obj, url){
	//console.log(user_info)
	let params = {
		method: 'api/v2/member_login/login_by_toutiao',
		code,
		encryptedData,
		iv,
		user_info: JSON.stringify(user_info)
	}
	http(params).then(res => {
		//console.log(res);
		if(res.status){
			uni.setStorageSync('nickname', user_info.nickName);
			uni.setStorageSync('headimg', user_info.avatarUrl);
			uni.setStorageSync('session_key', res.data.wx_data.session_key);
			uni.setStorageSync('openid', res.data.wx_data.openid);
			if(res.data.token){
				uni.hideLoading();
				store.commit('login', res.data.memberInfo);
				uni.setStorageSync('token', res.data.token);
				uni.setStorageSync('userInfo', res.data.memberInfo);
				obj.userInfo = {...res.data.memberInfo};
				obj.isLogin = obj.$store.state.hasLogin;
				if(url){
					uni.navigateTo({
						url: url
					})
				}
			}else{
				uni.hideLoading();
				uni.navigateTo({
					url: '/platforms/mp-toutiao/login/phone'
				})
			}
		}
	})
};

export default function(obj, url){
	let code;
	tt.getUserProfile({
		force: true,
		success(userRes) {
			tt.login({
				success: (loginRes) => {		
					if(loginRes.errMsg === 'login:ok'){
						code = loginRes.code;
						uni.showLoading({
							title: '登录中...'
						})
						requestUserInfo(code, userRes.encryptedData, userRes.iv, userRes.userInfo, obj, url)
					}
				}
			});
		},
		fail(userRes) {
			console.log(userRes)
		}
	})
	
	
}